<template>
  <div class="koi-flex">
    <KoiSearch :isFold="true" :showSearch="showSearch">
      <!-- 搜索条件 -->
      <el-form :inline="true">
        <el-form-item label="字典类型" prop="dictType">
          <el-select v-model="searchParams.dictType" clearable style="width: 220px" @change="handleChangeTable">
            <el-option v-for="item in dictOptions" :key="item.dictType" :label="item.dictName" :value="item.dictType" />
          </el-select>
        </el-form-item>
        <el-form-item label="字典名称" prop="dictLabel">
          <el-input
            placeholder="请输入字典名称"
            v-model="searchParams.dictLabel"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          ></el-input>
        </el-form-item>
        <el-form-item label="字典状态" prop="dictStatus">
          <el-select
            placeholder="请选择字典状态"
            v-model="searchParams.dictStatus"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          >
            <el-option :label="$t('dict.sys_switch_status.open')" value="0" />
            <el-option :label="$t('dict.sys_switch_status.stop')" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain @click="handleSearch()">{{ $t("button.search") }}</el-button>
          <el-button type="danger" icon="refresh" plain @click="resetSearch()">{{ $t("button.reset") }}</el-button>
        </el-form-item>
      </el-form>
    </KoiSearch>
    <KoiCard>
      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">{{ $t("button.add") }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="edit" plain @click="handleUpdate()" :disabled="single">{{
            $t("button.update")
          }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">{{
            $t("button.delete")
          }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="close" plain @click="handleBack()">{{ $t("button.close") }}</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
      </el-row>

      <div class="h-20px"></div>
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        border
        :data="tableList"
        :empty-text="$t('msg.null')"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column :label="$t('table.number')" prop="dictId" width="120px" align="center" type="index"></el-table-column>
        <el-table-column label="字典类型" prop="dictType" width="180px" align="center"></el-table-column>
        <el-table-column label="字典名称" prop="dictValue" width="160px" :show-overflow-tooltip="true" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="dictLabelOptions" :value="scope.row.dictValue"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column label="字典键值" prop="dictValue" width="120px" align="center"></el-table-column>
        <!-- 注意：如果后端数据返回的是字符串"0" OR "1"，这里的active-value AND inactive-value不需要加冒号，会认为是字符串，否则：后端返回是0 AND 1数字，则需要添加冒号 -->
        <el-table-column label="字典状态" prop="dictStatus" width="100px" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.dictStatus"
              :active-text="$t('dict.sys_switch_status.open')"
              :inactive-text="$t('dict.sys_switch_status.stop')"
              active-value="0"
              inactive-value="1"
              :inline-prompt="true"
              @change="handleSwitch(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="字典排序" prop="sorted" width="100px" align="center"></el-table-column>
        <el-table-column
          label="字典备注"
          prop="remark"
          width="260px"
          :show-overflow-tooltip="true"
          align="center"
        ></el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180px" align="center"></el-table-column>
        <el-table-column :label="$t('table.operate')" align="center" width="120" fixed="right">
          <template #default="{ row }">
            <el-tooltip :content="$t('button.update')" placement="top">
              <el-button type="primary" icon="Edit" circle plain @click="handleUpdate(row)"></el-button>
            </el-tooltip>
            <el-tooltip :content="$t('button.delete')" placement="top">
              <el-button type="danger" icon="Delete" circle plain @click="handleDelete(row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div class="h-20px"></div>
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 添加 OR 修改 -->
      <KoiDialog
        ref="koiDialogRef"
        :title="title"
        @koiConfirm="handleConfirm"
        @koiCancel="handleCancel"
        :loading="confirmLoading"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="auto" status-icon>
            <el-row :gutter="10">
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="字典名称" prop="dictLabel">
                  <el-input v-model="form.dictLabel" placeholder="请输入字典名称" maxlength="16" show-word-limit clearable />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="字典数据" prop="dictValue">
                  <el-input v-model="form.dictValue" placeholder="请输入字典数据" maxlength="16" show-word-limit clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="10">
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="标签类型" prop="dictTag">
                  <el-select v-model="form.dictTag" placeholder="请选择标签类型" clearable>
                    <el-option
                      v-for="item in tagOptions"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictTag"
                      clearable
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="字典状态" prop="dictStatus">
                  <el-select v-model="form.dictStatus" placeholder="请选择字典状态" clearable>
                    <el-option :label="$t('dict.sys_switch_status.open')" value="0" />
                    <el-option :label="$t('dict.sys_switch_status.stop')" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="标签样式" prop="dictClass">
                  <div class="flex flex-items-center w-full">
                    <el-tooltip
                      content="若选择标签样式会覆盖标签类型，否则选择空值"
                    >
                      <el-icon class="m-r-6px m-l--10px m-t-2px"><Warning /></el-icon>
                    </el-tooltip>
                    <div class="w-full">
                      <el-select
                        v-model="form.dictClass"
                        placeholder="请选择预设样式"
                        clearable
                        class="w-full"
                      >
                        <el-option v-for="style in presetStyles" :key="style.value" :label="style.label" :value="style.value">
                          <div class="flex flex-items-center flex-justify-between w-full">
                            <span>{{ style.label }}</span>
                            <div class="w-20px h-20px rounded-4px" :class="style.value"></div>
                          </div>
                        </el-option>
                      </el-select>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="字典排序" prop="sorted">
                  <el-input-number v-model="form.sorted" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="字典备注" prop="remark">
                  <el-input
                    v-model="form.remark"
                    :rows="3"
                    type="textarea"
                    placeholder="请输入字典备注"
                    maxlength="64"
                    show-word-limit
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </KoiDialog>
    </KoiCard>
  </div>
</template>

<script setup lang="ts" name="dictDataPage">
import { nextTick, ref, reactive, onMounted } from "vue";
import { koiMsgSuccess, koiMsgError, koiMsgWarning } from "@/utils/koi.ts";
import { ElMessageBox } from "element-plus";
import {
  listDictType,
  listPage,
  getById,
  add,
  update,
  deleteById,
  batchDelete,
  updateStatus,
  listDataByType,
  getSorted
} from "@/api/system/dict/data/index.ts";
import { useRouter, useRoute } from "vue-router";
import useTabsStore from "@/stores/modules/tabs.ts";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const tabsStore = useTabsStore();

// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true);
// 表格数据
const tableList = ref<any>([]);

// 查询参数
const searchParams = ref({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  dictType: undefined,
  dictLabel: undefined,
  dictStatus: undefined
});

const total = ref<number>(0);

/** 重置搜索参数 */
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    dictLabel: undefined,
    dictStatus: undefined,
    dictType: routeParam.value
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleChangeTable();
};

/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选择条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 数据表格[删除、批量删除等刷新使用] */
const handleTableData = async () => {
  try {
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 下拉框字典类型变化刷新页面 */
const handleChangeTable = () => {
  handleTableDict();
  handleListPage();
};

let routeParam = ref();

onMounted(() => {
  routeParam.value = route.params.dictType || ""; // 有值
  searchParams.value.dictType = routeParam.value;
  // 获取表格数据
  handleListPage();
  handleDictType();
  handleFormDict();
  handleTableDict();
});

// 下拉框数据
const tagOptions = ref<any>([]);

// 预设样式选项
const presetStyles = ref([
  {
    label: "空值",
    value: ""
  },
  {
    label: "橙色",
    value: "bg-#FFF7E9 text-#FFAE1F border-1px border-solid border-#FFE0B2 dark:bg-#301907 dark:border-#433316"
  },
  {
    label: "蓝色",
    value: "bg-#E6F3FF text-#1890FF border-1px border-solid border-#BBDEFB dark:bg-#111B26 dark:border-#1F2937"
  },
  {
    label: "绿色",
    value: "bg-#F6FFED text-#52C41A border-1px border-solid border-#C8E6C9 dark:bg-#162312 dark:border-#274916"
  },
  {
    label: "红色",
    value: "bg-#FFF2F0 text-#FF4D4F border-1px border-solid border-#FFCDD2 dark:bg-#2A1215 dark:border-#58181C"
  },
  {
    label: "紫色",
    value: "bg-#F9F0FF text-#722ED1 border-1px border-solid border-#E1BEE7 dark:bg-#120338 dark:border-#22075E"
  },
  {
    label: "青色",
    value: "bg-#E6FFFB text-#13C2C2 border-1px border-solid border-#B2EBF2 dark:bg-#102121 dark:border-#144B4B"
  },
  {
    label: "灰色",
    value: "bg-#FAFAFA text-#666666 border-1px border-solid border-#CFD8DC dark:bg-#262626 dark:border-#434343"
  },
  {
    label: "粉色",
    value: "bg-#FFF0F6 text-#EB2F96 border-1px border-solid border-#F8BBD9 dark:bg-#2D0B1A dark:border-#4A0B2E"
  },
  {
    label: "黄色",
    value: "bg-#FFFBE6 text-#FAAD14 border-1px border-solid border-#FFF59D dark:bg-#2A1F00 dark:border-#4A3500"
  },
  {
    label: "棕色",
    value: "bg-#FDF6E3 text-#8B4513 border-1px border-solid border-#D7CCC8 dark:bg-#1A0F00 dark:border-#2D1B00"
  },
  {
    label: "深蓝",
    value: "bg-#E3F2FD text-#1565C0 border-1px border-solid border-#BBDEFB dark:bg-#0D1B2A dark:border-#1B263B"
  },
  {
    label: "深绿",
    value: "bg-#E8F5E8 text-#2E7D32 border-1px border-solid border-#C8E6C9 dark:bg-#0A1F0A dark:border-#1A3D1A"
  },
  {
    label: "深红",
    value: "bg-#FFEBEE text-#C62828 border-1px border-solid border-#FFCDD2 dark:bg-#2A0A0A dark:border-#4A0A0A"
  },
  {
    label: "深紫",
    value: "bg-#F3E5F5 text-#6A1B9A border-1px border-solid border-#E1BEE7 dark:bg-#1A0A2A dark:border-#2A0A4A"
  },
  {
    label: "深青",
    value: "bg-#E0F2F1 text-#00695C border-1px border-solid border-#B2DFDB dark:bg-#0A1F1F dark:border-#1A3D3D"
  },
  {
    label: "深灰",
    value: "bg-#F5F5F5 text-#424242 border-1px border-solid border-#E0E0E0 dark:bg-#1A1A1A dark:border-#2A2A2A"
  },
  {
    label: "浅粉",
    value: "bg-#FFF8E1 text-#FF8F00 border-1px border-solid border-#FFECB3 dark:bg-#2A1F00 dark:border-#4A3500"
  },
  {
    label: "浅蓝",
    value: "bg-#F1F8E9 text-#689F38 border-1px border-solid border-#DCEDC8 dark:bg-#0F1A00 dark:border-#1F3A00"
  },
  {
    label: "浅绿",
    value: "bg-#E8F5E8 text-#388E3C border-1px border-solid border-#C8E6C9 dark:bg-#0A1F0A dark:border-#1A3D1A"
  },
  {
    label: "浅红",
    value: "bg-#FFEBEE text-#E53935 border-1px border-solid border-#FFCDD2 dark:bg-#2A0A0A dark:border-#4A0A0A"
  },
  {
    label: "浅紫",
    value: "bg-#F3E5F5 text-#8E24AA border-1px border-solid border-#E1BEE7 dark:bg-#1A0A2A dark:border-#2A0A4A"
  },
  {
    label: "浅青",
    value: "bg-#E0F2F1 text-#00838F border-1px border-solid border-#B2DFDB dark:bg-#0A1F1F dark:border-#1A3D3D"
  }
]);

/** 字典翻译下拉框 */
const handleFormDict = async () => {
  try {
    tagOptions.value = [];
    const res: any = await listDataByType("sys_tag_type");
    tagOptions.value = res.data;
  } catch (error) {
    console.log(error);
  }
};

// 下拉框数据
const dictLabelOptions = ref();

/** 字典翻译下拉框 */
const handleTableDict = async () => {
  try {
    dictLabelOptions.value = [];
    const res: any = await listDataByType(searchParams.value.dictType);
    dictLabelOptions.value = res.data;
  } catch (error) {
    console.log(error);
  }
};

// 字典类型名称下拉框
const dictOptions = ref();

/** 字典类型名称下拉框 */
const handleDictType = async () => {
  try {
    const res: any = await listDictType();
    dictOptions.value = res.data;
  } catch (error) {
    console.log(error);
  }
};

const ids = ref([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  console.log(selection);
  ids.value = selection.map((item: any) => item.dictId);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

// 获取最新排序数字
const handleSorted = async () => {
  try {
    const res: any = await getSorted(searchParams.value.dictType);
    form.value.sorted = res.data;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 添加 */
const handleAdd = () => {
  // 打开对话框
  koiDialogRef.value.koiOpen();
  // 重置表单
  resetForm();
  // 标题
  title.value = t("button.add");
  form.value.dictStatus = "0";
  form.value.dictType = searchParams.value.dictType;
  handleSorted();
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  try {
    const res: any = await getById(id);
    form.value = res.data;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 打开对话框
  koiDialogRef.value.koiOpen();
  // 重置表单
  resetForm();
  // 标题
  title.value = t("button.update");
  const dictId = row ? row.dictId : ids.value[0];
  // 回显数据
  handleEcho(dictId);
};

// 添加 OR 修改对话框Ref
const koiDialogRef = ref();
// 标题
const title = ref();
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  dictId: undefined,
  dictType: undefined,
  dictLabel: undefined,
  dictValue: undefined,
  dictStatus: undefined,
  dictTag: undefined,
  dictClass: undefined,
  sorted: 1,
  remark: undefined
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
  });
  form.value = {
    dictId: undefined,
    dictType: undefined,
    dictLabel: undefined,
    dictValue: undefined,
    dictStatus: undefined,
    dictTag: undefined,
    dictClass: undefined,
    sorted: 1,
    remark: undefined
  };
};

/** 表单规则 */
const rules = reactive({
  dictLabel: [{ required: true, message: "请输入字典名称", trigger: "blur" }],
  dictValue: [{ required: true, message: "请输入字典数据", trigger: "blur" }],
  dictTag: [{ required: true, message: "请输入选择标签类型", trigger: "blur" }],
  dictStatus: [{ required: true, message: "请输入选择字典状态", trigger: "blur" }]
});

// 确定按钮是否显示Loading
const confirmLoading = ref(false);

/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      if (form.value.dictId != null && form.value.dictId != "") {
        try {
          await update(form.value);
          koiMsgSuccess(t("msg.success"));
          confirmLoading.value = false;
          koiDialogRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiMsgError(t("msg.fail"));
        }
      } else {
        try {
          await add(form.value);
          koiMsgSuccess(t("msg.success"));
          confirmLoading.value = false;
          koiDialogRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiMsgError(t("msg.fail"));
        }
      }
      handleTableDict();
    } else {
      koiMsgError(t("msg.validFail"));
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDialogRef.value.koiClose();
};

/** 状态开关 */
const handleSwitch = (row: any) => {
  let text = row.dictStatus === "0" ? t("dict.sys_switch_status.open") : t("dict.sys_switch_status.stop");
  if (!row.dictId || !row.dictStatus) {
    row.dictStatus = row.dictStatus == "0" ? "1" : "0";
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmWant") + "[" + text + "]-[" + row.dictLabel + "]?", t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await updateStatus(row.dictId, row.dictStatus);
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        row.dictStatus = row.dictStatus == "0" ? "1" : "0";
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      row.noticeStatus = row.noticeStatus == "0" ? "1" : "0";
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.dictId;
  if (id == null || id == "") {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmDelete"), t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteById(id);
        handleTableData();
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 批量删除 */
const handleBatchDelete = () => {
  if (ids.value.length == 0) {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmDelete"), t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await batchDelete(ids.value);
        handleTableData();
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 关闭当前选项卡 */
const handleCloseCurrentTab = () => {
  if (route.meta?.isAffix == "0") return;
  tabsStore.removeTab(route.fullPath);
};

/** 返回 */
const handleBack = () => {
  handleCloseCurrentTab();
  router.push("/system/dict/type");
};
</script>

<style lang="scss" scoped></style>
